<template>
  <div>
    <el-header style="padding: 0;margin: 0">
      <el-affix :offset="0">
        <div id="headDiv">
          <div>
            <el-button type="warning" size="large" style="margin-left: 40px" @click="$router.push('app')" round>
              <el-icon>
                <House/>
              </el-icon>
              首页
            </el-button>
          </div>
          <div>
            <span style="color: #626262;margin-right: 20px">您好!</span>
            <el-button type="primary" size="large" @click="$router.push('goods')" round>全部商品</el-button>
            <el-button type="primary" size="large" @click="toShoppingCar()" round>购物车</el-button>
            <el-button size="large" type="primary" @click="toOrder()" round>个人订单</el-button>
            <el-button size="large" type="primary" @click="$router.push('user')" round>个人信息</el-button>
            <el-button size="large" type="primary" @click="$router.push('returnOrder')" round>
              退款订单管理
            </el-button>
            <el-button size="large" type="primary" @click="$router.push('userMoney')" round>预存款管理</el-button>
            <el-button size="large" type="danger" style="margin-right: 20px" @click="exitUser()" round>退出登录
            </el-button>
          </div>
        </div>
      </el-affix>
    </el-header>

    <div style="width: auto;height: auto;margin: 0 auto;">
      <div style="font-size: 30px;margin: 20px 0">
        <a href="#" style="color:#545454;text-decoration: none;">LO<span style="color: #c4c4c4">V</span><span>O</span> |
          朗沃商城</a>
      </div>
    </div>
    <div style="margin: 0 auto;width: auto;">
      <el-menu mode="horizontal" default-active="1">
        <el-menu-item index="1" @click="userMessage(1)">我的资料</el-menu-item>
        <el-menu-item index="2" @click="userMessage(2)">我的地址</el-menu-item>
        <!--        <el-menu-item index="3" @click="userMessage(3)">我的钱包</el-menu-item>-->
        <el-menu-item index="4" @click="userMessage(4)">修改密码</el-menu-item>
      </el-menu>
      <el-main>
        <!--用户基本资料-->
        <div :hidden="showUser">
          <div style="display: flex;justify-content: center;">
            <div style="margin-right: 150px">
              <h3 style="margin-bottom: 100px">用户名:</h3>
              <h4 style="margin-bottom: 100px">真实姓名:</h4>
              <!--            <h4 style="margin-bottom: 100px">性别:</h4>-->
              <h4 style="margin-bottom: 100px">电话号码:</h4>
              <h4>公司名称:</h4>
            </div>
            <div>
              <h3 style="margin-bottom: 100px">{{ userCon.userName }}</h3>
              <h4 style="width: 500px;margin-bottom: 100px">{{ userCon.userRealName }}</h4>
              <!--            <el-radio-group v-model="userCon.userGender" style="margin-bottom: 65px">-->
              <!--              <el-radio label="0">女</el-radio>-->
              <!--              <el-radio label="1">男</el-radio>-->
              <!--            </el-radio-group><br>-->
              <h4 style="width: 500px;margin-bottom: 100px">{{ userCon.userPhone }}</h4>
              <h4 style="width: 500px;">{{ userCon.companyName }}</h4>
              <!--            <el-button type="primary" style="margin-top: 20px">保存</el-button>-->
            </div>
          </div>
        </div>
        <!--   用户地址   -->
        <div :hidden="showAddress">
          <el-table :data="userAddress" style="width: auto;">
            <el-table-column label="收货人" prop="receiverName" align="center" width="180px"></el-table-column>
            <el-table-column label="所在地区" prop="receiverRegion" align="center" width="180px"></el-table-column>
            <el-table-column label="详细地址" prop="receiverAddress" align="center"  width="180px"></el-table-column>
            <el-table-column label="电话" prop="receiverPhone" align="center" width="180px"></el-table-column>
            <el-table-column label="操作" align="center" width="180px">
              <template #default="address">
                <el-button type="primary" @click="changeAddress(address.row)">修改</el-button>
                <el-button type="danger" @click="deleteAddress(address.row.addressId)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="地址" align="center ">
              <template #default="address">
                <el-button v-if="address.row.defaultAddress==0" @click="changeDefaultAddress(address.row)">
                  设为默认地址
                </el-button>
                <p v-else-if="address.row.defaultAddress==1">默认地址</p>
              </template>
            </el-table-column>
          </el-table>
          <div style="display:flex;justify-content: end;margin-top: 20px;margin-right: 65px">
            <el-button type="success" @click="showAdd">新增地址</el-button>
            <a :href="exportExcel" style="text-decoration: underline;text-decoration:none;margin-left: 10px">
              <el-button type="success">导出地址</el-button>
            </a>
            <el-upload
                class="upload-demo"
                action="api/address/importExcelAddress"
                accept=".xls, .xlsx"
                :headers="importExcelHeader"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="updateSuccess"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
            >
              <el-button type="primary" style="margin-left: 10px">导入地址</el-button>

            </el-upload>
          </div>
        </div>
        <!--  钱包    -->
        <div :hidden="showMoney">
          <div style="display: flex;justify-content: center;font-size: 25px;margin-top: 20px">
          <span style="margin: 0 100px">预存款余额:<span
              style="color:#da0f0f;margin-left: 20px"><strong>{{ userMoney.money }}</strong></span></span>
            <span v-if="userMoney.grade==1" style="margin: 0 100px">会员等级:<span
                style="color: #919191;margin-left: 20px"><strong>白银会员</strong></span></span>
            <span v-else-if="userMoney.grade==2" style="margin: 0 100px">会员等级:<span
                style="color: darkorange;margin-left: 20px"><strong>黄金会员</strong></span></span>
            <span v-else-if="userMoney.grade==3" style="margin: 0 100px">会员等级:<span
                style="color: #27e1bf;margin-left: 20px"><strong>铂金会员</strong></span></span>
            <span v-else-if="userMoney.grade==4" style="margin: 0 100px">会员等级:<span
                style="color: #24edff;margin-left: 20px"><strong>钻石会员</strong></span></span>
            <el-button type="danger" style="margin: 0 100px" @click="recharge">充值</el-button>
          </div>
          <div style="width: 100%;border-top: 1px gray solid;margin-top: 30px"></div>
          <div style="display:flex;justify-content: center;margin-top: 30px">
            <div style="margin: 0 100px;text-align: center">
              <h3>充值记录</h3>
              <el-table :data="rechargeRecord" style="width: 600px;">
                <el-table-column label="充值金额" prop="money" align="center"></el-table-column>
                <el-table-column label="充值时间" prop="time" align="center"></el-table-column>
              </el-table>
            </div>
            <div style="margin: 0 100px;text-align: center">
              <h3>消费记录</h3>
              <el-table :data="consume" style="width: 600px;">
                <el-table-column label="消费金额" prop="money" align="center"></el-table-column>
                <el-table-column label="消费时间" prop="time" align="center"></el-table-column>
              </el-table>
            </div>
          </div>
          <!--  预存款充值  -->
          <el-dialog v-model="showPay">
            <div style="display: flex;justify-content: space-between;">
              <el-input placeholder="自定义金额" v-model="rechargeMoney" style="width: 120px;" type="number"></el-input>
              <el-button>10</el-button>
              <el-button>50</el-button>
              <el-button>200</el-button>
              <el-button>1000</el-button>
              <el-button>5000</el-button>
              <el-button>20000</el-button>
              <div>
                <el-button type="primary">确认充值</el-button>
                <el-button @click="closeDiv">返回</el-button>
              </div>
            </div>
          </el-dialog>
        </div>
        <!--  修改密码  -->
        <div :hidden="showPassword">
          <div
              style="display: flex;justify-content: center;align-content: space-between;width: 600px;flex-wrap: wrap;margin: 0 auto">
            <el-form :model="changePwd" ref="changePwd" :rules="rules" label-width="500px" style="margin-right: 400px">
              <el-form-item prop="oldPwd">
              <span slot="label">
                <span style="font-size: 15px;">请输入您的旧密码:</span>
              </span>
                <el-input type="password" v-model="changePwd.oldPwd" style="width: 300px;"></el-input>
              </el-form-item>

              <el-form-item prop="newPwd">
            <span slot="label">
      	    <span style="font-size: 15px">请输入新密码:</span>
             </span>
                <el-input type="password" v-model="changePwd.newPwd" style="width: 300px;"></el-input>
              </el-form-item>

              <el-form-item prop="okNewPwd">
      <span slot="label">
      	<span style="font-size: 15px">请确定新密码:</span>
      </span>
                <el-input type="password" v-model="changePwd.okNewPwd" style="width: 300px;"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="update" style="margin-left: 100px">
                  <el-icon>
                    <EditPen/>
                  </el-icon>
                  修改密码
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!--新增地址-->
        <el-dialog v-model="addAddress" @close="closeDiv">
          <div style="display: flex;justify-content: center">
            <h2>新增收货地址</h2>
          </div>
          <div style="display: flex;justify-content: center;">
            <div style="margin-right: 100px;margin-bottom: 50px">
              <h3 style="margin-top: 20px">地址信息:</h3>
              <h3 style="margin-top: 75px">详细地址:</h3>
              <h3 style="margin-top: 75px">收货人姓名:</h3>
              <h3 style="margin-top: 80px">手机号码:</h3>
            </div>
            <div>
              <el-form :rules="addressRules" :model="address" ref="address">
                <el-form-item prop="receiverRegion">
                  <el-cascader size="large" :options="options" :props="cascaderProps" v-model="address.receiverRegion"
                               placeholder="请选择省/市/区" @change="handleChange"
                               style="width: 400px;margin-top: 15px"></el-cascader>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverAddress">
                  <el-input size="large" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
                            style="width: 400px;margin-top: 35px" v-model="address.receiverAddress"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverName">
                  <el-input size="large" placeholder="长度不超过25个字符" style="width: 400px;margin-top: 42px"
                            v-model="address.receiverName"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverPhone">
                  <el-input size="large" placeholder="中国大陆 +86" style="width: 400px;margin-top: 43px"
                            v-model="address.receiverPhone"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="defaultAddress">
                  <el-radio-group v-model="address.defaultAddress">
                    <el-radio :label="0">设置非默认地址</el-radio>
                    <el-radio :label="1">设置为默认地址</el-radio>
                  </el-radio-group>
                  <br>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <template #footer>
            <div style="margin-bottom: 50px">
              <el-button type="primary" @click="ackAdd">保存地址</el-button>
              <el-button @click="closeDiv" style="margin-right: 170px">取消</el-button>
            </div>
          </template>
        </el-dialog>
        <!--修改地址-->
        <el-dialog v-model="updateAddress" @close="closeDiv">
          <div style="display: flex;justify-content: center">
            <h2>修改收货地址</h2>
          </div>
          <div style="display: flex;justify-content: center;">
            <div style="margin-right: 100px;margin-bottom: 50px">
              <h3 style="margin-top: 20px">地址信息:</h3>
              <h3 style="margin-top: 75px">详细地址:</h3>
              <h3 style="margin-top: 75px">收货人姓名:</h3>
              <h3 style="margin-top: 80px">手机号码:</h3>
            </div>
            <div>
              <el-form :rules="addressRules" :model="address" ref="address">
                <el-form-item prop="receiverRegion">
                  <el-cascader size="large" :options="options" :props="cascaderProps" v-model="address.receiverRegion"
                               placeholder="请选择省/市/区" @change="handleChange"
                               style="width: 400px;margin-top: 15px"></el-cascader>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverAddress">
                  <el-input size="large" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
                            style="width: 400px;margin-top: 35px" v-model="address.receiverAddress"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverName">
                  <el-input size="large" placeholder="长度不超过25个字符" style="width: 400px;margin-top: 42px"
                            v-model="address.receiverName"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="receiverPhone">
                  <el-input size="large" placeholder="中国大陆 +86" style="width: 400px;margin-top: 43px"
                            v-model="address.receiverPhone"></el-input>
                  <br>
                </el-form-item>
                <el-form-item prop="defaultAddress">
                  <el-radio-group v-model="address.defaultAddress">
                    <el-radio :label="0">设置非默认地址</el-radio>
                    <el-radio :label="1">设置为默认地址</el-radio>
                  </el-radio-group>
                  <br>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <template #footer>
            <div style="margin-bottom: 50px">
              <el-button type="primary" @click="ackChange">保存地址</el-button>
              <el-button @click="closeDiv" style="margin-right: 170px">取消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-main>
    </div>
  </div>
</template>
<script>
import {regionData} from 'element-china-area-data';
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "User",
  data() {
    return {
      rechargeMoney: "",
      //导出excel
      exportExcel: 'api/address/exportExcelAddress?userNo=' + sessionStorage.getItem('userNo'),
      //导入excel
      importExcelHeader: {
        userNO: sessionStorage.getItem('userNo')
      },
      //全国地址
      options: regionData,
      //设置返回的地址内容
      cascaderProps: {
        value: "label"
      },
      selectedOptions: [],
      userCon: {},
      userAddress: [],
      userMoney: {
        money: 500000,
        grade: 4,
      },
      address: {
        defaultAddress: 0,
      },
      userPassword: {
        oldPassword: "", NewPassword: "", ackPassword: "",
      },
      rechargeRecord: [
        {money: 1000, time: "2023-05-01 14:20:26"},
        {money: 1600, time: "2023-05-01 14:20:26"},
        {money: 899, time: "2023-05-01 14:20:26"},
        {money: 50000, time: "2023-05-01 14:20:26"},
        {money: 10000, time: "2023-05-01 14:20:26"},
      ],
      consume: [
        {money: 388, time: "2023-05-01 14:20:26"},
        {money: 689, time: "2023-05-01 14:20:26"},
        {money: 25, time: "2023-05-01 14:20:26"},
        {money: 16780, time: "2023-05-01 14:20:26"},
        {money: 2000, time: "2023-05-01 14:20:26"},
      ],
      showUser: true,
      showAddress: true,
      showMoney: true,
      showPassword: true,
      showPay: false,
      addAddress: false,
      updateAddress: false,
      changePwd: {
        oldPwd: "",
        newPwd: "",
        okNewPwd: ""
      },
      addressRules: {
        receiverRegion: [
          {required: true, message: '请选择地址信息', trigger: 'blur'},
        ],
        receiverAddress: [
          {required: true, message: '请输入详细地址信息', trigger: 'blur'},
        ],
        receiverName: [
          {required: true, message: '请输入收货人', trigger: 'blur'},
        ],
        receiverPhone: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur'}
        ]
      },
      rules: {
        oldPwd: [
          {required: true, message: '请输入旧密码', trigger: 'blur'},
          {min: 2, max: 8, message: '密码长度为2-8位', trigger: 'blur'}],
        newPwd: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 2, max: 8, message: '密码长度为2-8位', trigger: 'blur'}],
        okNewPwd: [
          {required: true, message: '请输入确认密码', trigger: 'blur'},
          {min: 2, max: 8, message: '密码长度为2-8位', trigger: 'blur'}],
      },
      userToken: "",
      config: {},
    }
  },
  created() {
    let userToken = sessionStorage.getItem("userToken")
    if (userToken == null) {
      this.$router.push("login")
    } else {
      this.userToken = userToken
    }
    this.config = {
      headers: {
        'token': this.userToken
      }
    };
    this.userMessage(1);
    this.queryUser();

  },
  methods: {
    queryUser() {
      this.userCon = JSON.parse(sessionStorage.getItem('user'));
      console.log(this.userCon)
    },
    //地址选择器
    handleChange(value) {
      console.log(value)
    },
    //查询用户信息
    userMessage(tag) {
      if (tag == 1) {
        this.showUser = false
        this.showAddress = true
        this.showMoney = true
        this.showPassword = true
      } else if (tag == 2) {
        axios.get("api/address/queryAddress/?userNo=" + sessionStorage.getItem('userNo')).then(r => {
          console.log(r.data.data)
          if (r.data.data != null) {
            this.userAddress = r.data.data
          } else {
            this.userAddress = '';
            ElMessage.error(r.data.msg)
          }
        })
        this.showUser = true
        this.showAddress = false
        this.showMoney = true
        this.showPassword = true
      } else if (tag == 3) {
        this.showUser = true
        this.showAddress = true
        this.showMoney = false
        this.showPassword = true
      } else if (tag == 4) {
        this.showUser = true
        this.showAddress = true
        this.showMoney = true
        this.showPassword = false
      }
    },

    //新增地址
    showAdd() {
      this.addAddress = true
    },
    //改变默认地址
    changeDefaultAddress(addressRow) {
      addressRow.defaultAddress = 1
      axios.post('api/address/updateAddress', addressRow).then(p => {
        if (p.data.code == 200) {
          ElMessage.success(p.data.msg)
          this.userMessage(2)
        } else {
          ElMessage.error(p.data.msg)
        }
      })
    },
    //改变地址
    changeAddress(addressRow) {
      this.updateAddress = true;
      this.address.addressId = addressRow.addressId;
      this.address.receiverName = addressRow.receiverName;
      this.address.receiverPhone = addressRow.receiverPhone;
      let str = addressRow.receiverRegion.split('-');

      this.address.receiverRegion = [str[0], str[1], str[2],]


      console.log(this.address.receiverRegion)
      this.address.receiverAddress = addressRow.receiverAddress;
      this.address.defaultAddress = addressRow.defaultAddress;
      this.address.userNo = addressRow.userNo;
    },
    //确认改变地址
    ackChange() {
      let code = "";
      for (let i = 0; i < this.address.receiverRegion.length; i++) {
        code += this.address.receiverRegion[i] + "-"
      }

      this.address.receiverRegion = code.substring(0, code.length - 1);
      axios.post('api/address/updateAddress', this.address).then(p => {
        if (p.data.code == 200) {
          ElMessage.success(p.data.msg)
          this.userMessage(2)
          this.closeDiv();
          this.updateAddress = false;
        } else {
          ElMessage.error(p.data.msg)
          this.closeDiv();
          this.updateAddress = false;
        }
      })
    },
    //确认添加地址
    ackAdd() {
      let code = "";
      for (let i = 0; i < this.address.receiverRegion.length; i++) {
        code += this.address.receiverRegion[i] + "-"
      }
      this.address.receiverRegion = code.substring(0, code.length - 1);
      this.address.userNo = sessionStorage.getItem("userNo");
      console.log(this.address.userNo);
      axios.post("api/address/addAddress", this.address).then(r => {
        console.log(r.data)
        if (r.data.code == 200) {
          ElMessage.success(r.data.msg)
          this.userMessage(2);
          this.closeDiv();
        } else {
          ElMessage.error(r.data.msg)
          this.userMessage(2);
          this.closeDiv();
        }
      })
    },
    updateSuccess(){
      this.userMessage(2);
    },
    //删除收货地址
    deleteAddress(addressId) {
      axios.delete('api/address/deleteAddress?addressId=' + addressId).then(p => {
        if (p.data.code === 200) {
          ElMessage.success(p.data.msg)
          this.userMessage(2);
        } else {
          ElMessage.error(p.data.msg)
        }
      })
    },
    //退出登录
    exitUser() {
      sessionStorage.clear();
      this.$router.push("newLogin")
    },
    //关闭dialog
    closeDiv() {
      this.address = {
        defaultAddress: 0,
      }
      this.addAddress = false
      this.showPay = false;
      this.updateAddress = false;
    },
    //充值
    recharge() {
      this.showPay = true;
    },
    //修改密码
    update() {
      let params = new URLSearchParams();
      params.append("oldPwd", this.changePwd.oldPwd);
      if (this.changePwd.newPwd == this.changePwd.okNewPwd) {
        params.append("newPwd", this.changePwd.newPwd);
        params.append('userNo', sessionStorage.getItem('userNo'))
        this.$confirm('您确定要修改密码吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // let config = {
          //   headers: {
          //     'token': this.userToken
          //   }
          // }
          axios.post('/api/user/changePwd', params, this.config).then(resp => {
            if (resp.data.code == 200) {
              //this.$message.success(resp.data.data)
              //清空表单
              this.$refs.changePwd.resetFields();
              //退出登录
              this.$notify({
                title: '修改密码成功!',
                message: '请重新登录Lovo商城!!!',
                type: 'success'
              });
              this.exitUser();
            } else {
              this.$message.error(resp.data.msg)
              this.$refs.changePwd.resetFields();
            }
          })
        }).catch(() => {
          //用户点击取消按钮
          this.$message({
            type: 'info',
            message: '已取消修改密码!'
          });
        });
      } else {
        this.$message.error("请确定您的新密码与确认密码一致!")
      }
    },
    toShoppingCar(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('shoppingCar')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },
    toOrder(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('order')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },

  }
}
</script>

<style>
#headDiv {
  width: 100%;
  background-color: white;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 5px 10px gray;
}
</style>